ATOM Documentation

← Back to App

ATOM SaaS Billing & Subscription Management

This module handles the SaaS billing logic with Stripe integration, subscription management, and storage tracking.

🏗️ Architecture

Components:

  • **Subscription Service**: Stripe integration for billing
  • **Storage Tracker**: S3 usage monitoring per tenant
  • **Limit Enforcer**: Middleware to enforce plan limits
  • **Billing Engine**: Recurring charges and invoicing

💳 Pricing Plans

Free Tier

  • Price: $0/month
  • Storage: 5MB
  • Users: 3
  • Features: Basic AI, limited workflows
  • API Calls: 1,000/month

Pro Tier

  • Price: $29/month
  • Storage: 100MB
  • Users: 10
  • Features: Full AI, unlimited workflows, advanced integrations
  • API Calls: 10,000/month

Enterprise

  • Price: $99+/month
  • Storage: 1GB+
  • Users: Unlimited
  • Features: Everything + priority support, custom features
  • API Calls: Unlimited

📊 Storage Calculation

Storage Types Tracked:

  • Document uploads
  • AI conversation attachments
  • Workflow exports
  • User profile images
  • Backup files

Real-time Tracking:

# Track S3 usage per tenant
def track_storage_usage(tenant_id, file_size, file_type='upload'):
    # Update database
    update_storage_usage(tenant_id, file_size, file_type)
    
    # Check limits
    if exceeds_limit(tenant_id):
        raise StorageLimitExceeded()
    
    # Log to analytics
    analytics.track('storage_used', {
        'tenant_id': tenant_id,
        'size': file_size,
        'type': file_type
    })

🔄 Subscription Lifecycle

New Tenant Flow:

  1. Create tenant account (free tier)
  2. Verify email address
  3. Set up initial workspace
  4. Offer upgrade to paid plans

Upgrade Flow:

  1. User selects plan
  2. Redirect to Stripe Checkout
  3. Process payment
  4. Update tenant plan in database
  5. Grant additional features
  6. Send confirmation email

Downgrade Flow:

  1. User requests downgrade
  2. Pro-rate current subscription
  3. Schedule end of current period
  4. At period end: remove premium features
  5. Enforce new storage limits
  6. Notify user of changes

🛡️ Limit Enforcement

Storage Limits:

  • **Real-time check**: Before file upload
  • **Background job**: Recalculate S3 usage hourly
  • **Buffer**: 5% overage allowed with warning
  • **Grace period**: 7 days after limit exceeded

API Rate Limits:

  • **Free tier**: 100 calls/hour
  • **Pro tier**: 1,000 calls/hour
  • **Enterprise**: Unlimited

Feature Limits:

# Middleware to check feature access
@app.before_request
def check_feature_access():
    tenant_id = get_current_tenant()
    feature = request.endpoint
    
    if not feature_enabled(tenant_id, feature):
        return jsonify({'error': 'Feature not available in your plan'}), 403

📈 Revenue Metrics

Key Metrics Tracked:

  • **MRR**: Monthly Recurring Revenue
  • **ARR**: Annual Recurring Revenue
  • **Churn Rate**: Customer attrition percentage
  • **LTV**: Customer Lifetime Value
  • **CAC**: Customer Acquisition Cost

Dashboard Features:

  • Real-time revenue tracking
  • Customer growth metrics
  • Plan distribution analytics
  • Revenue forecasts

🔧 Integration Points

Stripe Webhooks:

  • customer.subscription.created - New subscription
  • customer.subscription.updated - Plan changes
  • customer.subscription.deleted - Cancellations
  • invoice.payment_succeeded - Successful payments
  • invoice.payment_failed - Payment failures

S3 Storage Events:

  • ObjectCreated events for tracking uploads
  • ObjectRemoved events for storage cleanup
  • Lifecycle policies for cost optimization

📝 Usage Examples

Create Subscription:

def create_subscription(tenant_id, plan_id):
    customer = stripe.Customer.create(
        email=get_tenant_email(tenant_id),
        metadata={'tenant_id': tenant_id}
    )
    
    subscription = stripe.Subscription.create(
        customer=customer.id,
        items=[{'price': plan_id}],
        payment_behavior='default_incomplete',
        expand=['latest_invoice.payment_intent'],
        metadata={'tenant_id': tenant_id}
    )
    
    return subscription

Check Storage Limit:

def check_storage_limit(tenant_id, upload_size):
    tenant = get_tenant(tenant_id)
    current_usage = get_storage_usage(tenant_id)
    
    if (current_usage + upload_size) > tenant.storage_limit_mb * 1024 * 1024:
        raise StorageLimitExceeded(
            current=current_usage,
            limit=tenant.storage_limit_mb,
            upload_size=upload_size
        )

🎯 Best Practices

  1. **Transparent Pricing**: Clear limits and overage charges
  2. **Gradual Upgrades**: Easy upgrade path with minimal friction
  3. **Graceful Degradation**: Don't immediately block users on limit breaches
  4. **Usage Analytics**: Help customers understand their usage patterns
  5. **Automated Billing**: Reduce manual intervention in billing process
  6. **Customer Communication**: Notify users before limits are reached
  7. **Data Retention**: Clear policies for data after downgrade/cancellation

🚨 Edge Cases

Payment Failures:

  • Retry logic with exponential backoff
  • Grace period for failed payments
  • Feature reduction before full suspension

Storage Overages:

  • Temporary overage allowance (5%)
  • Warning emails at 80%, 95%, 100% usage
  • Soft limits vs hard limits enforcement

Plan Changes: